package com.aliyun.messagemgt.web.controller;


import com.aliyun.messagemgt.application.service.ChannelService;
import com.aliyun.messagemgt.application.service.OperateLogService;
import com.aliyun.messagemgt.common.annotation.OperateLogAnnotation;
import com.aliyun.messagemgt.common.constants.MgtCommonConst;
import com.aliyun.messagemgt.common.enums.OperateTypeEnum;
import com.aliyun.messagemgt.common.enums.ResourceTypeEnum;
import com.aliyun.messagemgt.common.errorcode.CommonErrorCode;
import com.aliyun.messagemgt.common.exceptions.BaseException;
import com.aliyun.messagemgt.common.dto.response.ResultMap;
import com.aliyun.messagemgt.dto.OperateLog;
import com.aliyun.messagemgt.dto.PushChannelAdd;
import com.aliyun.messagemgt.dto.PushChannelList;
import com.aliyun.messagemgt.dto.query.PushChannelQuery;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author
 * @date
 */
@Api(tags = "渠道管理相关接口")
@CrossOrigin
@RestController
@RequestMapping(value = "/channel")
@Slf4j
public class ChannelController {

    @Autowired
    private ChannelService channelService;

    @Autowired
    private OperateLogService operateLogService;

    @RequestMapping("/save")
    public Object saveChannel(@RequestBody PushChannelAdd pushChannelAdd){
//        pushChannelAdd.setUseStatus(0);
        String description = pushChannelAdd.getDescription();
        boolean addFlag = pushChannelAdd.getPushChannelId() == null ? true : false;
        if(!addFlag){
            PushChannelQuery pushChannelQuery = new PushChannelQuery();
            pushChannelQuery.setPushChannelId(pushChannelAdd.getPushChannelId());
            PushChannelList pushChannelList = (PushChannelList)channelService.detailChannel(pushChannelQuery);
            description = pushChannelList.getDescription();
        }
        OperateLog operateLog = new OperateLog()
                .setOperateResourceType(ResourceTypeEnum.PUSHCHANNEL.getCode())
                .setModule(MgtCommonConst.MODULE_SMART_PUSH)
                .setOperateUser(pushChannelAdd.getUserId())
                .setOperateUserName(pushChannelAdd.getUserName())
                .setOperateDept(pushChannelAdd.getDepartment())
                .setOperateDeptName(pushChannelAdd.getDepartmentName())
                .setOperateTime(new Date())
                .setOperateResourceId(null)
                .setOperateResourceName(description);
        int i = 0;
        if (pushChannelAdd.getPushChannelId()!=null){
            try {
                operateLog.setOperateType(OperateTypeEnum.MOD.getCode());
                operateLog.setOperateResourceId(Math.toIntExact(pushChannelAdd.getPushChannelId()));
                i = (int)channelService.modPushChannel(pushChannelAdd);
                if(i <= 0){
                    operateLog.setFailMsg(CommonErrorCode.FAIL_UPDATE_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
                }else{
                    operateLog.setFailMsg(CommonErrorCode.SUCCESS_UPDATE_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
                }
            }catch (Exception e){
                operateLog.setFailMsg(CommonErrorCode.FAIL_UPDATE_CHANNEL.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
                if(e instanceof BaseException){
                    throw e;
                }else{
                    throw new RuntimeException("操作失败！");
                }
            }finally {
                operateLogService.insertOperateLog(operateLog);
            }
        }else{
            try{
                operateLog.setOperateType(OperateTypeEnum.SAVE.getCode());
                i = (int)channelService.savePushChannel(pushChannelAdd);
                if(i <= 0){
                    operateLog.setFailMsg(CommonErrorCode.FAIL_ADD_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
                }else{
                    operateLog.setFailMsg(CommonErrorCode.FAIL_ADD_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
                }
            }catch (Exception e){
                operateLog.setFailMsg(CommonErrorCode.FAIL_ADD_CHANNEL.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);

                if(e instanceof BaseException){
                    throw e;
                }else{
                    throw new RuntimeException("操作失败！");
                }
            }finally {
                operateLogService.insertOperateLog(operateLog);
            }
        }
        return i;
    }

    @RequestMapping("/commit")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.PUSHCHANNEL ,operateType = OperateTypeEnum.COMMIT,
            resouceClass = PushChannelAdd.class,resouceIdField = "pushChannelId")
    public Object commitChannel(@RequestBody PushChannelAdd pushChannelAdd){
//        pushChannelAdd.setUseStatus(1);
        String description = pushChannelAdd.getDescription();
        boolean addFlag = pushChannelAdd.getPushChannelId() == null ? true : false;
        if(!addFlag){
            PushChannelQuery pushChannelQuery = new PushChannelQuery();
            pushChannelQuery.setPushChannelId(pushChannelAdd.getPushChannelId());
            PushChannelList pushChannelList = (PushChannelList)channelService.detailChannel(pushChannelQuery);
            description = pushChannelList.getDescription();
        }
        OperateLog operateLog = new OperateLog()
                .setOperateResourceType(ResourceTypeEnum.PUSHCHANNEL.getCode())
                .setModule(MgtCommonConst.MODULE_SMART_PUSH)
                .setOperateUser(pushChannelAdd.getUserId())
                .setOperateUserName(pushChannelAdd.getUserName())
                .setOperateDept(pushChannelAdd.getDepartment())
                .setOperateDeptName(pushChannelAdd.getDepartmentName())
                .setOperateTime(new Date())
                .setOperateResourceId(null)
                .setOperateResourceName(description);
        int i = 0;
        if (pushChannelAdd.getPushChannelId()!=null){
            try {
                operateLog.setOperateType(OperateTypeEnum.COMMIT.getCode());
                operateLog.setOperateResourceId(Math.toIntExact(pushChannelAdd.getPushChannelId()));
                i = (int)channelService.modPushChannel(pushChannelAdd);
                if(i <= 0){
                    operateLog.setFailMsg(CommonErrorCode.FAIL_PUBLISH_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
                }else{
                    operateLog.setFailMsg(CommonErrorCode.SUCCESS_PUBLISH_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
                }
            } catch (Exception e) {
                log.error("update channel errer=={}",e);
                operateLog.setFailMsg(CommonErrorCode.FAIL_PUBLISH_CHANNEL.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
                if(e instanceof BaseException){
                    throw e;
                }else{
                    throw new RuntimeException("操作失败！");
                }
            }finally {
                operateLogService.insertOperateLog(operateLog);
                }
        }else{
            try{
                pushChannelAdd.setUserCreate("-1");
                pushChannelAdd.setUserUpdate("-1");

                operateLog.setOperateType(OperateTypeEnum.COMMIT.getCode());
                i = (int)channelService.commitPushChannel(pushChannelAdd);
                if(i <= 0){
                    operateLog.setFailMsg(CommonErrorCode.FAIL_PUBLISH_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
                }else{
                    operateLog.setFailMsg(CommonErrorCode.SUCCESS_PUBLISH_CHANNEL.errName());
                    operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
                }
            } catch (Exception e) {
                log.info("commitChannel e=={}", e);
                operateLog.setFailMsg(CommonErrorCode.FAIL_PUBLISH_CHANNEL.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);

                if(e instanceof BaseException){
                    throw e;
                }else{
                    throw new RuntimeException("操作失败！");
                }
            }finally {
                operateLog.setOperateUser("-1");
                operateLog.setOperateUserName("-1");
                operateLogService.insertOperateLog(operateLog);
            }
        }
        return i;
    }

    @ApiOperation("渠道测试")
    @PostMapping(value = "/test")
    @ApiResponses({
            @ApiResponse(code = 200, message = "1:成功，0：失败")
    })
    public Object test(@RequestBody PushChannelAdd pushChannelAdd){
        return channelService.testCsbConnection(pushChannelAdd);
    }

    @RequestMapping("/del")
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.PUSHCHANNEL ,operateType = OperateTypeEnum.DEL,
            resouceClass = PushChannelQuery.class,resouceIdField = "pushChannelId")
    public Object delChannel(@RequestBody PushChannelQuery pushChannelQuery){
        PushChannelList pushChannelList = (PushChannelList)channelService.detailChannel(pushChannelQuery);
        if(pushChannelList == null){
            throw new BaseException(CommonErrorCode.FAIL_DELETE_CHANNEL);
        }
        OperateLog operateLog = new OperateLog()
                .setOperateResourceType(ResourceTypeEnum.PUSHCHANNEL.getCode())
                .setModule(MgtCommonConst.MODULE_SMART_PUSH)
                .setOperateUser(pushChannelQuery.getUserId())
                .setOperateUserName(pushChannelQuery.getUserName())
                .setOperateDept(pushChannelQuery.getDepartment())
                .setOperateDeptName(pushChannelQuery.getDepartmentName())
                .setOperateTime(new Date())
                .setOperateResourceId(null)
                .setOperateResourceName(pushChannelList.getDescription());
        int i = 0;

        try {
            operateLog.setOperateType(OperateTypeEnum.DEL.getCode());
            operateLog.setOperateResourceId(Math.toIntExact(pushChannelQuery.getPushChannelId()));
            i = (int)channelService.delPushChannel(pushChannelQuery);
            if(i <= 0){
                operateLog.setFailMsg(CommonErrorCode.FAIL_DELETE_CHANNEL.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
            }else{
                operateLog.setFailMsg(CommonErrorCode.SUCCESS_DELETE_CHANNEL.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
            }
        }catch (Exception e){
            operateLog.setFailMsg(CommonErrorCode.FAIL_PUBLISH_CHANNEL.errName());
            operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
            throw new RuntimeException("该渠道已被使用，不可删除");
        }finally {
            operateLogService.insertOperateLog(operateLog);
        }
        return i;
    }

    @PostMapping("/list")
    public Object listChannel(@RequestBody PushChannelQuery pushChannelQuery){
        return channelService.listPushChannel(pushChannelQuery);
    }

    /**
     * 顶置功能
     */
    @RequestMapping("/top")
    public Object topChannel(@RequestBody PushChannelQuery pushChannelQuery){
        return channelService.topChannel(pushChannelQuery);
    }

    /**
     * 查询详情
     */
    @RequestMapping("/detail")
    public Object detailChannel(@RequestBody PushChannelQuery pushChannelQuery){
        return channelService.detailChannel(pushChannelQuery);
    }

    @RequestMapping("/channelsTypes")
    public ResultMap channelsTypes(@RequestBody PushChannelQuery pushChannelQuery){
        return new ResultMap(channelService.channelsTypes(pushChannelQuery));
    }

    @RequestMapping("/updateStatus")
    public Object updateStatus(@RequestBody PushChannelQuery pushChannelQuery) {
        Long pushChannelId = pushChannelQuery.getPushChannelId();
        Integer useStatus = pushChannelQuery.getUseStatus();
        if (pushChannelId == null || useStatus == null) {
            throw new BaseException(CommonErrorCode.COMMON_PARAM_INVALID);
        }
        return channelService.updateStatus(pushChannelQuery);
    }
}
